package com.oa.sig.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.audit.log.client.annotation.AuditLog;
import com.mdp.audit.log.client.annotation.OperType;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.sig.entity.SigSeal;
import com.oa.sig.entity.SigSealDto;
import com.oa.sig.entity.SigSealSignet;
import com.oa.sig.service.SigSealService;
import com.oa.sig.service.SigSealSignetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/sig/sigSeal")
@Api(tags = {"用印申请表-操作接口"})
public class SigSealController {

    static Logger logger = LoggerFactory.getLogger(SigSealController.class);

    @Autowired
    private SigSealService sigSealService;
    @Autowired
    private SigSealSignetService sigSealSignetService;

    @ApiOperation(value = "用印申请表-查询列表", notes = " ")
    @ApiEntityParams(SigSeal.class)
    @ApiResponses({@ApiResponse(code = 200, response = SigSeal.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listSigSeal(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        String branchId = LoginUtils.getCurrentUserInfo().getBranchId();
        params.put("sealBranchId", branchId);
        QueryWrapper<SigSeal> qw = QueryTools.initQueryWrapper(SigSeal.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> sigSealList = sigSealService.selectListMapByWhere(page, qw, params);
        for (Map<String, Object> sealMap : sigSealList) {
            String sealId = (String) sealMap.get("id");
            List<Map<String, Object>> sigSealSignets = sigSealSignetService.selectListBySealId(sealId);
            sealMap.put("sigSealSignets", sigSealSignets);
        }
        return Result.ok("query-ok", "查询成功").setData(sigSealList).setTotal(page.getTotal());
    }


    @ApiOperation(value = "用印申请表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = SigSeal.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addSigSeal(@RequestBody SigSeal sigSeal) {
        if (StringUtils.isEmpty(sigSeal.getId())) {
            sigSeal.setId(sigSealService.createKey("id"));
        } else {
            SigSeal sigSealQuery = new SigSeal(sigSeal.getId());
            if (sigSealService.countByWhere(sigSealQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        sigSealService.insert(sigSeal);
        return Result.ok("add-ok", "添加成功！").setData(sigSeal);
    }

    @ApiOperation(value = "用印申请表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delSigSeal(@RequestBody SigSeal sigSeal) {
        int i = sigSealService.deleteByPk(sigSeal);
        if (i == 1) {
//            sigSealSignetService.deleteBySealId(sigSeal.getId());
            SigSealSignet sigSealSignet = new SigSealSignet();
            sigSealSignet.setSealId(sigSeal.getId());
            sigSealSignetService.deleteByWhere(sigSealSignet);
        }
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "用印申请表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = SigSeal.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editSigSeal(@RequestBody SigSeal sigSeal) {
        sigSealService.updateByPk(sigSeal);
        return Result.ok("edit-ok", "修改成功！").setData(sigSeal);
    }

    @ApiOperation(value = "用印申请表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = SigSeal.class, props = {}, remark = "用印申请表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = SigSeal.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        sigSealService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "用印申请表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelSigSeal(@RequestBody List<SigSeal> sigSeals) {
        User user = LoginUtils.getCurrentUserInfo();
        if (sigSeals.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<SigSeal> datasDb = sigSealService.listByIds(sigSeals.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<SigSeal> can = new ArrayList<>();
        List<SigSeal> no = new ArrayList<>();
        for (SigSeal data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            sigSealService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }
        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "用印申请表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = SigSeal.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(SigSeal sigSeal) {
        SigSeal data = sigSealService.getById(sigSeal);
        return Result.ok().setData(data);
    }

    /**
     * 新增用印和用印材料
     *
     * @param sigSealDto
     * @return
     */
    @RequestMapping(value = "/addSigSealAndSealSigne", method = RequestMethod.POST)
    public Result addSigSealAndSealSignet(@RequestBody SigSealDto sigSealDto) throws ParseException {
        sigSealService.addSigSealAndSealSignet(sigSealDto);
        return Result.ok();
    }

    /**
     * 修改sigseal并修改sigsealsignet
     *
     * @param sigSealDto
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/editSigSealAndSigSealSignet", method = RequestMethod.POST)
    public Result editSigSealAndSigSealSignet(@RequestBody SigSealDto sigSealDto) throws ParseException {
        sigSealService.editSigSealAndSigSealSignet(sigSealDto);
        return Result.ok();
    }

    /**
     * 流程审批过程中回调该接口，更新业务数据
     * 如果发起流程时上送了restUrl，则无论流程中是否配置了监听器都会在流程发生以下事件时推送数据过来
     * eventName: PROCESS_STARTED 流程启动完成 全局
     * PROCESS_COMPLETED 流程正常结束 全局
     * PROCESS_CANCELLED 流程删除 全局
     * create 人工任务启动
     * complete 人工任务完成
     * assignment 人工任务分配给了具体的人
     * delete 人工任务被删除
     * <p>
     * 其中 create/complete/assignment/delete事件是需要在模型中人工节点上配置了委托代理表达式 ${taskBizCallListener}才会推送过来。
     * 在人工任务节点上配置 任务监听器  建议事件为 complete,其它assignment/create/complete/delete也可以，一般建议在complete,委托代理表达式 ${taskBizCallListener}
     *
     * @param flowVars {flowBranchId,agree,procInstId,assignee,actId,taskName,mainTitle,branchId,bizKey,commentMsg,eventName,modelKey} 等
     * @return 如果tips.isOk==false，将影响流程提交
     **/
    @AuditLog(firstMenu = "办公平台", secondMenu = "用印申请", func = "processApprova", funcDesc = "用印审核流程", operType = OperType.UPDATE)
    @RequestMapping(value = "/processApprova", method = RequestMethod.POST)
    public Result processApprova(@RequestBody Map<String, Object> flowVars) {
        QueryWrapper<SigSeal> qw = QueryTools.initQueryWrapper(SigSeal.class, flowVars);
        IPage page = QueryTools.initPage(flowVars);
        sigSealService.processApprova(page, qw, flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));
        return Result.ok();
    }
}
